import 'package:flutter/cupertino.dart';

/// FileName change_text_editing_controller
///
/// @Author lax
/// @Date 2023/9/7
///
/// @Description 处理iOS原生键盘输入问题

class ChangeTextEditingController extends TextEditingController {
  var completeText = '';

  String? lastText;

  ChangeTextEditingController.fromValue(TextEditingValue value)
      : super.fromValue(value);

  @override
  TextSpan buildTextSpan({required BuildContext context, TextStyle? style , required bool withComposing}) {
    // 拼音输入完成
    if (!value.composing.isValid || !withComposing) {
      if (completeText != value.text) {
        completeText = value.text;
        WidgetsBinding.instance.addPostFrameCallback((_) {
          notifyListeners();
        });
      }
      return TextSpan(style: style, text: text);
    }

    // 返回输入样式，可自定义样式
    final TextStyle? composingStyle = style?.merge(
      const TextStyle(decoration: TextDecoration.underline),
    );
    return TextSpan(
      style: style,
      children: <TextSpan>[
        TextSpan(text: value.composing.textBefore(value.text)),
        TextSpan(
          style: composingStyle,
          text: value.composing.isValid && !value.composing.isCollapsed
              ? value.composing.textInside(value.text)
              : "",
        ),
        TextSpan(text: value.composing.textAfter(value.text)),
      ],
    );
  }
}
